<template>
  <div class="message-center-container">
    <div class="message-center-title">
      <i class="fks-title-icon" />
      <span>{{ LANG.MESSAGE_LIST }}</span>
      <fks-button class="message-read-all" @click="readAllMsg">
        {{ LANG.READ_ALL_MESSAGE }}
      </fks-button>
    </div>
    <fks-alert
      v-show="showRefreshText"
      class="new-message-alert"
      :title="LANG.HAS_NEW_MESSAGE"
      type="warning"
      :closable="false"
      show-icon
      @click.native="refreshMsgList"
    />
    <div
      id="messageListContainer"
      ref="messageListContainer"
      v-loading="TABLE_LOADING"
      class="message-list-container"
    >
      <div v-show="tableData.length <= 0" class="message-list-no-message" />
      <div
        v-show="tableData.length > 0"
        id="messageList"
        ref="messageList"
        class="message-list"
      >
        <fks-collapse v-model="activeName" accordion @change="clickHandle">
          <fks-collapse-item
            v-for="(item, index) in tableData"
            :key="index"
            :name="index + 1"
          >
            <template slot="title">
              <div
                class="message-item"
                :class="{ 'has-read': item.status == 0 }"
                :style="activeName == index + 1 ? 'border:none;' : ''"
              >
                <div class="message-stauts">
                  <div class="status-icon" />
                </div>
                <span
                  class="message-simple-content"
                  :style="activeName == index + 1 ? 'color: #555;' : ''"
                  >{{
                    activeName == index + 1
                      ? LANG.COMPLETE_MESSAGE + '：'
                      : item.text
                  }}</span
                >
                <div class="message-date">
                  <span>{{ item.createDate }}</span>
                </div>
              </div>
            </template>
            <div class="message-complete-content">
              <span v-html="item.msgBody" />
            </div>
          </fks-collapse-item>
        </fks-collapse>
      </div>
      <div class="loadmore" :class="[isLastPage ? 'is-over' : 'is-load']">
        <div
          v-loading="moreLoading"
          :element-loading-custom-class="'message-list-loadmore'"
          :element-loading-text="LANG.LOADING"
        />
        <span v-if="isLastPage">{{ LANG.NO_MORE_MESSAGE }}</span>
      </div>
    </div>

    <div class="message-center-bottom" />
  </div>
</template>

<script>
import { USER } from '@/store/State/stateTypes'
import { RECEIVED_MESSAGE } from '@/store/State/stateTypes'
import { CHECK_UNREAD_MESSAGE } from '@/store/Action/actionTypes'
import { UPDATE_RECEIVED_MESSAGE } from '@/store/Mutation/mutationTypes'
import { getMsgByIdAndName, updateMsgStatusById } from '@/api/message.js'
import throttle from 'throttle-debounce/throttle'

export default {
  name: 'MessageCenter',

  data() {
    return {
      searchFrom: {},
      tableData: [], //消息列表表格数据
      msgList: [],
      pageNo: 1,
      pageSize: 25,
      total: 0,
      selectRows: [],
      templateList: [],
      TABLE_LOADING: false,
      isLastPage: false,
      moreLoading: false,
      showRefreshText: false,

      box: null,
      activeName: '-1',

      subscription: {},

      realDestination: '/user/topic/message',

      HASREAD: 0,
      UNREAD: -1,
      DELETE: -2
    }
  },
  computed: {
    receivedMessage() {
      return this.$store.state[RECEIVED_MESSAGE]
    },
    USER() {
      return this.$store.state[USER]
    },
    msgType() {
      return this.$store.state.enum.msgType
    },
    msgStatus() {
      return this.$store.state.enum.msgStatus
    }
  },

  watch: {
    receivedMessage: {
      handler(newVal) {
        if (newVal) {
          this.onNewMessageHandle()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.initData()
    this.box = this.$refs.messageListContainer
    this.box.onscroll = this.scrollHandler
  },
  methods: {
    onNewMessageHandle() {
      if (this.showRefreshText) return
      this.showRefreshText = true
    },
    refreshMsgList() {
      this.showRefreshText = false
      this.$store.commit(UPDATE_RECEIVED_MESSAGE, false)
      this.initData()
    },
    /**
     * @description: 点击后展开/合上，未读的更新为已读;
     */
    clickHandle(activeNum) {
      if (!activeNum || activeNum == 0) return

      let item = this.tableData[activeNum - 1]

      if (item.isUnFold) this.$set(item, 'isUnFold', false)
      else {
        this.$set(item, 'isUnFold', true)
        //模拟手风琴，打开一个关闭其他
        this.tableData.forEach((message) => {
          if (message.id != item.id) {
            this.$set(message, 'isUnFold', false)
          }
        })
      }

      if (item.status != this.HASREAD) {
        this.updateStatus(item, this.HASREAD)
        this.$set(item, 'status', this.HASREAD)
      }
    },
    /**
     * @description: 根据字典，将消息类型码转为文本
     * @param {*} code
     * @return {*}
     */
    tranTypeFromCodeToText(code) {
      let typeCode = ''
      switch (true) {
        case code == '100':
          typeCode = '100'
          break
        case code < 300 && code >= 200:
          typeCode = '200'
          break
        case code == '300':
          typeCode = '300'
          break
        case code == '400':
          typeCode = '400'
          break
        // default:
        //   typeCode = ''
      }

      let type = this.msgType.find((item) => {
        return item.code == typeCode
      })
      if (type) return type[this.$lang]
      return ''
    },
    /**
     * @description: 根据字典，将消息状态码转为文本
     * @param {*} code
     * @return {*}
     */
    tranStatusFromCodeToText(code) {
      let status = this.msgStatus.find((item) => {
        return item.code == code
      })
      if (status) return status[this.$lang]
      return ''
    },
    handleSelectionChange(rows) {
      this.selectRows = rows
    },
    transDate(date) {
      let str = date.substring(0, date.length - 9)
      return str
    },

    /**
     * @description: 批量操作消息
     * @param {String} status:read/del  操作类型
     */
    multiOperation(status) {
      if (this.selectRows.length == 0) {
        this.$message({
          showClose: true,
          message: this.LANG.NO_CHOSEN_MSG,
          type: 'error'
        })
        return
      }
      let receiveLogIdList = []
      this.selectRows.forEach((item) => {
        receiveLogIdList.push(item.receiveLogId)
      })

      this.confirmUpdateStatus(receiveLogIdList.join(), status)
    },

    /**
     * @description: 所有消息已读
     */
    readAllMsg() {
      this.confirmUpdateStatus('all', this.HASREAD)
        .then((res) => {
          if (res.status) {
            this.tableData.forEach((message) => {
              this.$set(message, 'status', this.HASREAD)
            })
          }
        })
        .catch(() => {})
    },
    /**
     * @description:单条更新消息状态
     * @param {Object,String}
     */
    updateStatus(row, status) {
      if (row.status == status) return
      this.confirmUpdateStatus(row.receiveLogId, status)
    },

    /**
     * @description: 状态更新二次确认
     * @param {String} receiveLogIdList 要操作的消息的id拼接而成
     * @param {String} status 操作类型
     */
    confirmUpdateStatus(receiveLogIdList, status) {
      let temp = {
        receiveLogIdList: receiveLogIdList,
        status: status
      }
      if (status == this.DELETE) {
        //二次确认
        this.$confirm(this.LANG.DELETE_CONFIRM, this.LANG.TIPS, {
          type: 'warning',
          confirmButtonText: this.LANG.DELETE,
          cancelButtonText: this.LANG.CANCEL,
          confirmButtonClass: 'fks-button--danger',
          deleteMode: true
        })
          .then(() => {
            return this.updateMsgStatusById(temp)
          })
          .catch(() => {})
      } else {
        return this.updateMsgStatusById(temp)
      }
    },

    updateMsgStatusById(temp) {
      return updateMsgStatusById(temp)
        .then((res) => {
          this.$store.dispatch(CHECK_UNREAD_MESSAGE)
          return res
        })
        .catch(() => {})
    },

    /**
     * @description: 获取下一页数据
     */
    showNextPage: async function () {
      this.pageNo++
      this.moreLoading = true

      await this.getMsgByIdAndName()
      let newMsgList = this.dealData(this.msgList)

      //拼接并去重
      newMsgList = this.tableData.concat(newMsgList)
      this.tableData = [...new Set(newMsgList)]

      this.moreLoading = false
    },
    /**
     * @description: 获取初始数据
     */
    getList: async function () {
      this.TABLE_LOADING = true
      await this.getMsgByIdAndName()
      this.tableData = this.dealData(this.msgList)
      this.TABLE_LOADING = false
    },
    getMsgByIdAndName() {
      let temp = {
        currentPage: this.pageNo,
        pageSize: this.pageSize,
        title: this.searchFrom.title,
        status: this.searchFrom.status,
        startDate: this.searchFrom.startDate,
        endDate: this.searchFrom.endDate
      }
      switch (this.searchFrom.msgTypeForSearch) {
        case '100':
          temp.type = '100'
          break
        case '200':
          temp.type = '200-299'
          break
        case '300':
          temp.type = '300'
          break
        case '400':
          temp.type = '400'
          break
        default:
          temp.type = ''
      }

      return getMsgByIdAndName(temp)
        .then((res) => {
          if (res.status) {
            this.isLastPage = res.data.isLastPage
            this.msgList = [...res.data.list]
            this.total = res.data.total
          }
        })
        .catch(() => {
          this.msgList = []
        })
    },

    dealData(list) {
      let newList = list.map((item) => {
        item.text = this.removeTag(item.msgBody)
        return item
      })
      return newList
    },

    /**
     * @description: 去除富文本的标签只获得文本内容
     */
    removeTag(str = '') {
      if (!str) return ''
      let fn_result = str.replace(/<[^<>]+>/g, '').replace(/&nbsp;/gi, '')
      return fn_result
    },

    /**
     * @description: 分页响应
     */
    pageSizeChange(size) {
      this.pageSize = size
      this.initData()
    },
    pageChange(page) {
      this.pageNo = page
      this.initData()
    },
    search() {
      this.pageNo = 1
      this.getList()
    },
    clear() {
      this.initData()
    },
    clearData() {
      this.pageNo = 1
      this.searchFrom = {}
      this.tableData = []
      this.msgList = []
      this.selectRows = []
      this.isLastPage = false
    },
    initData() {
      this.clearData()
      this.getList()
    },
    scrollHandler: throttle(1000, function (e) {
      //如果是最后一页直接return
      if (this.isLastPage) {
        return
      }
      //如果加载中，也直接return
      if (this.moreLoading) {
        return
      }

      let dataDom = document.getElementById('messageList')
      if (
        dataDom.clientHeight - this.box.scrollTop - this.box.clientHeight <=
        400
      ) {
        this.showNextPage()
      }
    })
  }
}
</script>

<style scoped lang="scss">
.message-center-container {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  // padding: 24px 32px;
  background: #fff;
}

.message-center-title {
  position: relative;
  display: flex;
  flex-shrink: 0;
  align-items: center;
  padding: 24px 0 16px;
  margin: 0 32px;
  border-bottom: 1px solid #eee;
  font-weight: bold;
  font-size: 16px;
  color: #191919;

  .message-read-all {
    position: absolute;
    right: 0;
  }
}

.message-list-container {
  flex-grow: 1;
  width: 100%;
  padding: 0 32px;
  overflow-y: scroll;
}

.message-list {
  position: relative;

  .fks-collapse {
    border: none;
  }
}

.message-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  overflow: hidden;
  line-height: 48px;
  cursor: pointer;

  // border-bottom: 1px solid #eeeeee;

  .message-stauts {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 48px;
    margin: 0 16px;

    .status-icon {
      width: 6px;
      height: 6px;
      border-radius: 100%;
      background: #ff4d4f;
    }
  }

  .message-simple-content {
    flex-grow: 1;
    height: 48px;
    font-size: 14px;
    color: #555;
  }

  .message-date {
    flex-shrink: 0;
    width: 148px;
    margin: 0 32px;
    font-weight: 400;
    font-size: 14px;
    font-family: Roboto-Regular, Roboto, sans-serif;
    color: #555;
  }

  .message-icon {
    color: #333;
  }

  &.has-read {
    .status-icon {
      background: #ccc;
    }

    .message-simple-content {
      color: #999;
    }

    .message-date {
      color: #999;
    }
  }
}

.message-center-bottom {
  flex-shrink: 0;
  width: 100%;
  height: 24px;
}

.message-complete-content {
  min-height: 48px;
  margin-left: 38px;
  font-size: 14px;
  color: #555;
}

.loadmore {
  margin-top: 16px;
  text-align: center;

  span {
    font-weight: 400;
    font-size: 14px;
    font-family: PingFangSC, PingFangSC-Regular, sans-serif;
    line-height: 20px;
    text-align: center;
    letter-spacing: 1px;
    user-select: none;
  }

  &.is-load {
    margin-top: 32px;
  }

  &.is-over span {
    color: #999;
  }
}

::v-deep .message-list-loadmore {
  .fks-loading-spinner {
    display: flex;
    justify-content: center;
    align-items: center;

    svg {
      width: 16px;
      height: 16px;
    }

    p {
      margin-left: 8px;
    }
  }
}

.new-message-alert {
  flex-shrink: 0;
  width: unset;
  margin: 8px 24px;
  border: unset;
  cursor: pointer;
}
</style>
